from flask import Flask
import sys
sys.path.append("/")
from app.config import config
from app.extensions import db, migrate, jwt, ma, cache, mail
from app.errors import register_error_handlers
from app.utils.logger import configure_logging
from app.api.v1 import register_blueprints
from app.models.user import Role, User, Department, FinancialBusiness


def create_app(config_name='default'):
    app = Flask(__name__)

    # 加载配置

    app.config.from_object(config[config_name])


    # 初始化扩展
    initialize_extensions(app)

    # 注册蓝图
    register_blueprints(app)

    # 注册错误处理器
    register_error_handlers(app)

    # 配置日志
    configure_logging(app)

    # 初始化数据库
    with app.app_context():
        db.create_all()

    mail.init_app(app)

    register_cli(app)

    return app


def initialize_extensions(app):
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    ma.init_app(app)
    cache.init_app(app, config={'CACHE_TYPE': 'RedisCache', 'CACHE_REDIS_URL': app.config.get('REDIS_URL')})

    # JWT配置回调
    @jwt.token_in_blocklist_loader
    def check_if_token_revoked(jwt_header, jwt_payload):
        from .models.user import TokenBlocklist
        jti = jwt_payload["jti"]
        token = TokenBlocklist.query.filter_by(jti=jti).first()
        return token is not None

def register_cli(app):
    @app.cli.command()
    def create_init_role():
        Role.init_role()

    @app.cli.command()
    def create_init_user():
        User.init_user()

    @app.cli.command()
    def create_init_department():
        Department.init_department()

    @app.cli.command()
    def create_init_financial():
        FinancialBusiness.init_financial_business()